package com.star.mall.base.response;

import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;

/**
 * 全局异常处理类
 * @author StarQ
 * @since 2021-03-21
 */
@ControllerAdvice(basePackages = "com.star.mall")
@Log4j2
public class BaseExceptionAdvice {

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public BaseResponse<Serializable> runtimeException(RuntimeException exception) {
        exception.printStackTrace();
        return new BaseResponse<>(ResponseCode.RUNTIME_ERROR, exception.getMessage(),null);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResponse<Serializable> doMethodArgumentNotValidException2(MethodArgumentNotValidException ex){
        String errorMessage = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数错误：{}", errorMessage);
        return new BaseResponse<>(ResponseCode.RUNTIME_ERROR, errorMessage,null);
    }

}
